package com.jinzhi.jzapi.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.utils.ApiResult;
import com.jinzhi.jzweb.dao.JzPaperQuestionPracticeRecordDao;
import com.jinzhi.jzweb.domain.JzPaperPracticeRecordDO;
import com.jinzhi.jzweb.domain.JzPaperQuestionPracticeRecordDO;
import com.jinzhi.jzapi.service.JzPaperPracticeRecordService;
import com.jinzhi.jzapi.service.JzPaperQuestionPracticeRecordService;
import com.jinzhi.sys.domain.UserDO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.jinzhi.api.util.TokenTag.TOKEN_TAG;

/**
 * (JzPaperPracticeRecord)表控制层
 *
 * @author makejava
 * @since 2025-03-10 11:16:35
 */
@Slf4j
@RestController
@RequestMapping("/jzApi/jzPaperPracticeRecord")
public class JzPaperPracticeRecordController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private JzPaperPracticeRecordService jzPaperPracticeRecordService;

    @Resource
    private JzPaperQuestionPracticeRecordService jzPaperQuestionPracticeRecordService;

    @Resource
    private JzPaperQuestionPracticeRecordDao jzPaperQuestionPracticeRecordDao;



    /**
     * 小程序新增练习记录
     *
     * @Description:
     * @Param: []
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-25
     */
    @PostMapping("/addPaper")
    @Log("小程序新增练习记录")
    @ResponseBody
    @Transactional
    @ApiOperation(value = "考试程序端-小程序新增练习记录", httpMethod = "Post", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> addPaper(@RequestHeader(value = TOKEN_TAG, required = false) String token,@RequestBody JzPaperPracticeRecordDO jzPaperPracticeRecordDO) {

        UserDO user = getClientUser(token);
        JzPaperPracticeRecordDO paperPracticeRecordDO=new JzPaperPracticeRecordDO();
        paperPracticeRecordDO.setCreaterId(user.getId());
        paperPracticeRecordDO.setName(jzPaperPracticeRecordDO.getName());
        paperPracticeRecordDO.setPaperId(jzPaperPracticeRecordDO.getPaperId());
        paperPracticeRecordDO.setCreaterDate(new Date());
        List<JzPaperQuestionPracticeRecordDO> list = jzPaperPracticeRecordDO.getList();
        paperPracticeRecordDO.setQuestionSize(list.size());
        jzPaperPracticeRecordService.insert(paperPracticeRecordDO);

        List<JzPaperQuestionPracticeRecordDO> processedList = list.stream()
                .peek(e -> {
                    if (!StringUtils.isEmpty(e.getValue())) {
                        e.setValue(e.getValue().replaceAll(";", "")); // 去除 value 中的分号
                    }
                })
                .map(record -> {
                    if (StringUtils.isEmpty(record.getValue()) || !record.getValue().equals(record.getAnswer())) {
                        // 如果 value 为空或者不等于 answer，将 score 设置为 0，isAnswer 设置为 1
                        record.setScore(0);
                        record.setIsAnswer(1);
                    } else {
                        // 如果 value 等于 answer，保持原有的 score，isAnswer 设置为 0
                        record.setIsAnswer(0);
                    }
                    // 确保 practiceId 已经设置（假设它是从原始数据中来的）
                    // 这里不需要额外的操作，除非需要对 practiceId 进行特殊处理
                    return record;
                })
                .collect(Collectors.toList());
        // 打印结果以验证
        for (JzPaperQuestionPracticeRecordDO record : processedList) {
            System.out.println("Value: " + record.getValue()
                    + ", Answer: " + record.getAnswer()
                    + ", Score: " + record.getScore()
                    + ", PracticeId: " + record.getPracticeId()
                    + ", IsAnswer: " + record.getIsAnswer());
        }

        // 计算总分数
        int totalScore = processedList.stream()
                .mapToInt(JzPaperQuestionPracticeRecordDO::getScore)
                .sum();
        paperPracticeRecordDO.setScore(totalScore);
        jzPaperPracticeRecordService.updateById(paperPracticeRecordDO);
        processedList.forEach(e->{
            e.setPaperRecordId(paperPracticeRecordDO.getId());
        });

        jzPaperQuestionPracticeRecordService.insertBatch(processedList);
        return ApiResult.success("你的分数", totalScore);
    }

    /**
     * api小程序端-练习记录详情
     *
     * @Description: 站点信息列表查询，参数：页码，显示数，站点名称（筛选条件），站点类型（筛选条件）
     * @Param: [current, number, name, type]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-04
     */
    @GetMapping("/selPaperInfo")
    @Log("api小程序端-练习记录详情")
    @ApiOperation(value = "api小程序端-练习记录详情", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> selPaperInfo(@RequestHeader(value = TOKEN_TAG, required = false) String token,Long id) {
        UserDO user = getClientUser(token);
        JzPaperPracticeRecordDO paperPracticeRecordDO = jzPaperPracticeRecordService.selectById(id);
        Map map = new HashMap();
        map.put("score", paperPracticeRecordDO.getScore());
        List<JzPaperQuestionPracticeRecordDO> list = jzPaperQuestionPracticeRecordService.selectList(new EntityWrapper<JzPaperQuestionPracticeRecordDO>().eq("paper_record_id", id));
        List<JzPaperQuestionPracticeRecordDO> collect = list.stream().filter(e -> e.getIsAnswer().equals(0)).collect(Collectors.toList());
        List<JzPaperQuestionPracticeRecordDO> collect1 = list.stream().filter(e -> e.getIsAnswer().equals(1)).collect(Collectors.toList());

        map.put("isTrue", collect.size());
        map.put("isFalse",  collect1.size());
        map.put("size",  collect1.size()+collect.size());
        return ApiResult.success(map);

    }

    /**
     * api小程序端-练习记录列表
     *
     * @Description: 站点信息列表查询，参数：页码，显示数，站点名称（筛选条件），站点类型（筛选条件）
     * @Param: [current, number, name, type]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-04
     */
    @GetMapping("/selPaperList")
    @Log("api小程序端-练习记录列表")
    @ApiOperation(value = "api小程序端-练习记录列表", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> selPaperList(@RequestHeader(value = TOKEN_TAG, required = false) String token,Long id) {
        UserDO user = getClientUser(token);
        List<JzPaperPracticeRecordDO> list = jzPaperPracticeRecordService.selectList(new EntityWrapper<JzPaperPracticeRecordDO>().eq("creater_id", user.getId()).eq("paper_id",id).orderBy("creater_date",false));
        return ApiResult.success(list);
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(Long id) {
        return ResponseEntity.ok(this.jzPaperPracticeRecordService.deleteById(id));
    }

}

